<?php

App::uses('AppController', 'Controller');

/**
 * Users Controller
 *
 * @property User $User
 * @property PaginatorComponent $Paginator
 * @property SessionComponent $Session
 */
class UsersController extends AppController {

    /**
     * Components
     *
     * @var array
     */
    public $components = array('Paginator', 'Session');

    /**
     * em_index method
     *
     * @return void
     */
    public function em_index() {
        $this->User->recursive = 0;
        $this->set('users', $this->Paginator->paginate());
    }

    /**
     * em_view method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function em_view($id = null) {
        if (!$this->User->exists($id)) {
            throw new NotFoundException(__('Invalid user'));
        }
        $options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
        $this->set('user', $this->User->find('first', $options));
    }

    /**
     * em_add method
     *
     * @return void
     */
    public function em_register() {
        // echo $this->Session->read('level');
        //$this->Session->write('level', 4);
        if (!$this->Session->read('level')) {
            $this->Session->write('level', 1);
        }
        // echo $this->Session->read('level');
        if ($this->request->is('post', 'ajax')) {
            //debug($this->request->data);exit;
            switch ($this->Session->read('level')) {
                case 1:
                    $this->pre_register();
                    break;
                case 2:
                    $this->em_add();
                    break;
                case 3:
                    $this->em_add_address();
                    break;
                case 4:
                    $this->em_add_eligibility();
                    break;
                case 5:
                    $this->em_add_school();
                    break;
                case 6:
                    $this->em_add_releases();
                    break;
                case 7:
                    $this->em_add_additional_info();
                    break;
            }
        }
        switch ($this->Session->read('level')) {
            case 1:
                // $this->pre_register();
                break;
            case 2:
                $maritalStatuses = $this->User->MaritalStatus->find('list');
                $genders = $this->User->Gender->find('list');
                $ethincities = $this->User->Ethincity->find('list');
                $carriers = $this->User->Carrier->find('list');
                $roles = $this->User->Role->find('list');
                $this->set(compact('maritalStatuses', 'genders', 'ethincities', 'carriers', 'roles'));
                break;
            case 3:
                $this->loadModel('Address');
                $states = $this->Address->State->find('list');
                $this->set(compact('states'));
                break;
            case 4:
                $this->loadModel('UserUnion');
                $unions = $this->UserUnion->Union->find('list');
                $this->set(compact('unions'));
                break;
            case 5:
                $this->loadModel('UserSchool');
                $states = $this->UserSchool->State->find('list');
                $schoolTypes = $this->UserSchool->SchoolType->find('list');
                $this->set(compact('states', 'schoolTypes'));
                break;
            case 6:
                $this->loadModel('WaiversRelease');
                $states = $this->WaiversRelease->State->find('list');
                $this->set(compact('states'));
            case 7:

                break;
        }
    }
    public function em_profile($id = null) {
    if (!$this->User->exists($id)) {
            throw new NotFoundException(__('Invalid user'));
        }
        $options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
        $this->set('user', $this->User->find('first', $options));
       
    }
    /**
     * em_add method
     *
     * @return void
     */
    public function em_add() {
        if ($this->request->is('post')) {
            //debug($this->request->data); //exit;
            $i = 0;
            $total = count($this->request->data['User']);
            foreach ($this->request->data['User'] as $user) {
                //debug($user);
                if (is_array($user['alternate_contact'])) {
                    if (count($user['alternate_contact']) == 2) {
                        $user['alternate_contact'] = 'Both';
                    } elseif (count($user['alternate_contact']) == 1) {
                        if ($user['alternate_contact'][0] == 'Texting') {
                            $user['alternate_contact'] = 'Texting';
                        } elseif ($user['alternate_contact'][0] == 'Post Mail') {
                            $user['alternate_contact'] = 'Post Mail';
                        }
                    }
                } else {
                    $user['alternate_contact'] = 'None';
                }
                $this->User->create();
                if ($this->User->save($user)) {
                    $i++;
                    if ($i == 1) {
                        $this->Session->write('UserID', $this->User->id);
                    }
                }
            }
            if ($i == $total) {
                $this->Session->setFlash(__('The user has been saved.'));
                $level = $this->Session->read('level') + 1;
                $user['profile_status'] = $level;
                $user['id'] = $this->Session->read('UserID');
                $this->User->save($user);
                $this->Session->write('level', $level);
                return $this->redirect($_SERVER['HTTP_REFERER']);
            } else {
                $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
            }
        }
    }

    public function em_add_address() {
        $this->loadModel('Address');
        $this->autoRender = false;
        $total = count($this->request->data['Address']);
        $i = 0;

        if ($this->request->is('post', 'ajax')) {
            foreach ($this->request->data['Address'] as $address) {
                $i++;
                $address['user_id'] = $this->Session->read('UserID');
                $this->Address->create();
                if ($this->Address->save($address)) {
                    
                }
            }
            if ($i == $total) {
                $msg = 'The address has been saved.';
                if ($this->request->is('ajax')) {
                    echo $msg;
                } else {
                    $this->Session->setFlash(__($msg));
                    $level = $this->Session->read('level') + 1;
                    $user['profile_status'] = $level;
                    $user['id'] = $this->Session->read('UserID');
                    $this->User->save($user);
                    $this->Session->write('level', $level);
                    return $this->redirect($_SERVER['HTTP_REFERER']);
                }
            } else {
                $msg = 'The address could not be saved. Please, try again.';
                if ($this->request->is('ajax')) {
                    echo $msg;
                } else {
                    $this->Session->setFlash(__($msg));
                }
            }
        }
    }

    public function em_secondary_address() {
        $this->layout = 'ajax';
        $this->loadModel('Address');
        $states = $this->Address->State->find('list');
        $this->set(compact('states'));
    }

    public function em_add_eligibility() {
        if ($this->request->is('post', 'ajax')) {
            $this->loadModel('UserAgent');
            $this->UserAgent->create();
            $this->request->data['UserAgent']['user_id'] = $this->Session->read('UserID');
            $this->UserAgent->save($this->request->data['UserAgent']);
            $this->loadModel('UserUnion');
            $i = 0;
            $total = count($this->request->data['UserUnion']);
            foreach ($this->request->data['UserUnion'] as $union) {
                if (isset($union['non_union_docs'])) {
                    unset($union['non_union_docs']);
                }
                $union['user_id'] = $this->Session->read('UserID');
                $this->UserUnion->create();
                if ($this->UserUnion->save($union)) {
                    $i++;
                }
            }
            if ($i == $total) {
                $msg = 'The user union has been saved.';
                if ($this->request->is('ajax')) {
                    echo $msg;
                } else {
                    $level = $this->Session->read('level') + 1;
                    $user['profile_status'] = $level;
                    $user['id'] = $this->Session->read('UserID');
                    $this->User->save($user);
                    $this->Session->write('level', $level);
                    $this->Session->setFlash(__($msg));
                    return $this->redirect($_SERVER['HTTP_REFERER']);
                }
            } else {
                $msg = 'The user union could not be saved. Please, try again.';
                if ($this->request->is('ajax')) {
                    echo $msg;
                } else {
                    $this->Session->setFlash(__($msg));
                }
            }
        }
    }

    public function add_union($count) {
        $this->layout = 'ajax';
        $this->loadModel('UserUnion');
        $unions = $this->UserUnion->Union->find('list');
        $this->set(compact('unions', 'count'));
    }

    public function em_add_school() {
        if ($this->request->is('post', 'ajax')) {
            $this->loadModel('UserSchool');
            //debug($this->request->data);
            $i = 0;
            $total = count($this->request->data['UserSchool']);
            //exit;
            foreach ($this->request->data['UserSchool'] as $school) {
                $school['user_id'] = $this->Session->read('UserID');
                $this->UserSchool->create();
                if ($this->UserSchool->save($school)) {
                    $i++;
                    // debug($school);
                }
            }
            //exit;
            if ($i == $total) {
                $msg = 'The user school has been saved.';
                if ($this->request->is('ajax')) {
                    echo $msg;
                } else {
                    $this->Session->setFlash(__($msg));
                    $level = $this->Session->read('level') + 1;
                    $user['profile_status'] = $level;
                    $user['id'] = $this->Session->read('UserID');
                    $this->User->save($user);
                    $this->Session->write('level', $level);
                    return $this->redirect($_SERVER['HTTP_REFERER']);
                }
            } else {
                $msg = 'The user school could not be saved. Please, try again.';
                if ($this->request->is('ajax')) {
                    echo $msg;
                } else {
                    $this->Session->setFlash(__($msg));
                }
            }
        }
    }

    public function add_school($count) {
        $this->layout = 'ajax';
        $this->loadModel('UserSchool');
        $states = $this->UserSchool->State->find('list');
        $schoolTypes = $this->UserSchool->SchoolType->find('list');
        $this->set(compact('states', 'schoolTypes', 'count'));
    }

    public function em_add_releases() {
        if ($this->request->is('post', 'ajax')) {
            $this->loadModel('WaiversRelease');
            $this->WaiversRelease->create();
            if ($this->WaiversRelease->save($this->request->data)) {
                $msg = 'The waivers release has been saved.';
                if ($this->request->is('ajax')) {
                    echo $msg;
                } else {
                    $this->Session->setFlash(__($msg));
                    $level = $this->Session->read('level') + 1;
                    $user['profile_status'] = $level;
                    $user['id'] = $this->Session->read('UserID');
                    $this->User->save($user);
                    $this->Session->write('level', $level);
                    return $this->redirect($_SERVER['HTTP_REFERER']);
                }
            } else {
                $msg = 'The waivers release could not be saved. Please, try again.';
                if ($this->request->is('ajax')) {
                    echo $msg;
                } else {
                    $this->Session->setFlash(__($msg));
                }
            }
        }
    }

    /**
     * admin_add method
     *
     * @return void
     */
    public function em_add_additional_info() {
        if ($this->request->is('post')) {
            $this->loadModel('AdditionalInfo');
            $this->request->data['AdditionalInfo']['user_id'] = $this->Session->read('UserID');
            //debug($this->request->data);exit;
            $this->AdditionalInfo->create();
            if ($this->AdditionalInfo->save($this->request->data)) {
                //$this->Session->setFlash(__('The additional info has been saved.'));
                $user['profile_status'] = 100;
                $user['id'] = $this->Session->read('UserID');
                $this->User->save($user);
                $this->Session->write('level', 8);
                return $this->redirect($_SERVER['HTTP_REFERER']);
            } else {
                $this->Session->setFlash(__('The additional info could not be saved. Please, try again.'));
            }
        }
        $users = $this->AdditionalInfo->User->find('list');
        $this->set(compact('users'));
    }

    public function add_parent_form($count = 0) {
        $this->layout = 'ajax';
        $maritalStatuses = $this->User->MaritalStatus->find('list');
        $genders = $this->User->Gender->find('list');
        $ethincities = $this->User->Ethincity->find('list');
        $carriers = $this->User->Carrier->find('list');
        $this->set(compact('maritalStatuses', 'genders', 'ethincities', 'carriers', 'count'));
    }

    /**
     * em_edit method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function em_edit($id = null) {
        if (!$this->User->exists($id)) {
            throw new NotFoundException(__('Invalid user'));
        }
        if ($this->request->is(array('post', 'put'))) {
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash(__('The user has been saved.'));
                return $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
            }
        } else {
            $options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
            $this->request->data = $this->User->find('first', $options);
        }
        $maritalStatuses = $this->User->MaritalStatus->find('list');
        $genders = $this->User->Gender->find('list');
        $ethincities = $this->User->Ethincity->find('list');
        $carriers = $this->User->Carrier->find('list');
        $roles = $this->User->Role->find('list');
        $this->set(compact('maritalStatuses', 'genders', 'ethincities', 'carriers', 'roles'));
    }

    /**
     * em_delete method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function em_delete($id = null) {
        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        $this->request->allowMethod('post', 'delete');
        if ($this->User->delete()) {
            $this->Session->setFlash(__('The user has been deleted.'));
        } else {
            $this->Session->setFlash(__('The user could not be deleted. Please, try again.'));
        }
        return $this->redirect(array('action' => 'index'));
    }

    /**
     * parent_index method
     *
     * @return void
     */
    public function parent_index() {
        $this->User->recursive = 0;
        $this->set('users', $this->Paginator->paginate());
    }

    /**
     * parent_view method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function parent_view($id = null) {
        if (!$this->User->exists($id)) {
            throw new NotFoundException(__('Invalid user'));
        }
        $options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
        $this->set('user', $this->User->find('first', $options));
    }

    /**
     * em_add method
     *
     * @return void
     */
    public function parent_register() {
        //echo $this->Session->read('level');
        //$this->Session->write('level', 1);
        if (!$this->Session->read('level')) {
            $this->Session->write('level', 1);
        }
        //echo $this->Session->read('level');
        if ($this->request->is('post', 'ajax')) {

            switch ($this->Session->read('level')) {
                case 1:
                    $this->pre_register();
                    break;
                case 2:
                    $this->parent_add();
                    break;
                case 3:
                    $this->yp_add();
                    break;
                case 4:
                    $this->em_add_address();
                    break;
                case 5:
                    $this->em_add_eligibility();
                    break;
                case 6:
                    $this->em_add_school();
                    break;
                case 7:
                    $this->em_add_releases();
                    break;
            }
        }
        switch ($this->Session->read('level')) {
            case 1:
                // $this->pre_register();
                break;
            case 2:
                $maritalStatuses = $this->User->MaritalStatus->find('list');
                $genders = $this->User->Gender->find('list');
                $ethincities = $this->User->Ethincity->find('list');
                $carriers = $this->User->Carrier->find('list');
                $roles = $this->User->Role->find('list');
                $this->set(compact('maritalStatuses', 'genders', 'ethincities', 'carriers', 'roles'));
                break;
            case 3:
                $maritalStatuses = $this->User->MaritalStatus->find('list');
                $genders = $this->User->Gender->find('list');
                $ethincities = $this->User->Ethincity->find('list');
                $carriers = $this->User->Carrier->find('list');
                $roles = $this->User->Role->find('list');
                $this->set(compact('maritalStatuses', 'genders', 'ethincities', 'carriers', 'roles'));
                break;
            case 4:
                $this->loadModel('Address');
                $states = $this->Address->State->find('list');
                $this->set(compact('states'));
                break;
            case 5:
                $this->loadModel('UserUnion');
                $unions = $this->UserUnion->Union->find('list');
                $this->set(compact('unions'));
                break;
            case 6:
                $this->loadModel('UserSchool');
                $states = $this->UserSchool->State->find('list');
                $schoolTypes = $this->UserSchool->SchoolType->find('list');
                $this->set(compact('states', 'schoolTypes'));
                break;
            case 7:
                $this->loadModel('WaiversRelease');
                $states = $this->WaiversRelease->State->find('list');
                $this->set(compact('states'));
                break;
        }
    }

    /**
     * parent_add method
     *
     * @return void
     */
    public function parent_add() {
        $this->layout = 'ajax';
        if ($this->request->is('post', 'ajax')) {
            //debug($this->request->data);
            $i = 0;
            $total = count($this->request->data);
            foreach ($this->request->data['User'] as $user) {
                $i++;
                if (!empty($user['alternate_contact'])) {
                    if (count($user['alternate_contact']) == 2) {
                        $user['alternate_contact'] = 'Both';
                    } elseif (count($user['alternate_contact']) == 1) {
                        if ($user['alternate_contact'][0] == 'Texting') {
                            $user['alternate_contact'] = 'Texting';
                        } elseif ($user['alternate_contact'][0] == 'Post Mail') {
                            $user['alternate_contact'] = 'Post Mail';
                        }
                    }
                } else {
                    $user['alternate_contact'] == 'None';
                }
                $this->User->create();
                if ($this->User->save($user)) {
                    if ($i == 1) {
                        $this->Session->write('UserID', $this->User->id);
                    }
                    if ($i == $total) {
                        $this->Session->setFlash(__('The user has been saved.'));
                        $user['profile_status'] = 3;
                        $user['id'] = $this->Session->read('UserID');
                        $this->User->save($user);
                        $this->Session->write('level', 3);
                        return $this->redirect($_SERVER['HTTP_REFERER']);
                    }
                } else {
                    $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
                }
            }
            //exit;
        }
    }

    public function yp_add() {
        $this->layout = 'ajax';
        if ($this->request->is('post', 'ajax')) {
            $this->User->create();
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash(__('The user has been saved.'));
                $user['profile_status'] = 4;
                $user['id'] = $this->Session->read('UserID');
                $this->User->save($user);
                $this->Session->write('level', 4);
                return $this->redirect($_SERVER['HTTP_REFERER']);
            } else {
                $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
            }
        }
    }

    /**
     * parent_edit method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function parent_edit($id = null) {
        if (!$this->User->exists($id)) {
            throw new NotFoundException(__('Invalid user'));
        }
        if ($this->request->is(array('post', 'put'))) {
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash(__('The user has been saved.'));
                return $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
            }
        } else {
            $options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
            $this->request->data = $this->User->find('first', $options);
        }
        $maritalStatuses = $this->User->MaritalStatus->find('list');
        $genders = $this->User->Gender->find('list');
        $ethincities = $this->User->Ethincity->find('list');
        $carriers = $this->User->Carrier->find('list');
        $roles = $this->User->Role->find('list');
        $this->set(compact('maritalStatuses', 'genders', 'ethincities', 'carriers', 'roles'));
    }

    /**
     * parent_delete method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function parent_delete($id = null) {
        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        $this->request->allowMethod('post', 'delete');
        if ($this->User->delete()) {
            $this->Session->setFlash(__('The user has been deleted.'));
        } else {
            $this->Session->setFlash(__('The user could not be deleted. Please, try again.'));
        }
        return $this->redirect(array('action' => 'index'));
    }

    /**
     * admin_index method
     *
     * @return void
     */
    public function admin_index() {
        $this->User->recursive = 0;
        $this->set('users', $this->Paginator->paginate());
    }

    /**
     * admin_view method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function admin_view($id = null) {
        if (!$this->User->exists($id)) {
            throw new NotFoundException(__('Invalid user'));
        }
        $options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
        $this->set('user', $this->User->find('first', $options));
    }

    /**
     * admin_add method
     *
     * @return void
     */
    public function admin_add() {
        if ($this->request->is('post')) {
            $this->User->create();
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash(__('The user has been saved.'));
                return $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
            }
        }
        $maritalStatuses = $this->User->MaritalStatus->find('list');
        $genders = $this->User->Gender->find('list');
        $ethincities = $this->User->Ethincity->find('list');
        $carriers = $this->User->Carrier->find('list');
        $roles = $this->User->Role->find('list');
        $this->set(compact('maritalStatuses', 'genders', 'ethincities', 'carriers', 'roles'));
    }

    /**
     * admin_edit method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function admin_edit($id = null) {
        if (!$this->User->exists($id)) {
            throw new NotFoundException(__('Invalid user'));
        }
        if ($this->request->is(array('post', 'put'))) {
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash(__('The user has been saved.'));
                return $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
            }
        } else {
            $options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
            $this->request->data = $this->User->find('first', $options);
        }
        $maritalStatuses = $this->User->MaritalStatus->find('list');
        $genders = $this->User->Gender->find('list');
        $ethincities = $this->User->Ethincity->find('list');
        $carriers = $this->User->Carrier->find('list');
        $roles = $this->User->Role->find('list');
        $this->set(compact('maritalStatuses', 'genders', 'ethincities', 'carriers', 'roles'));
    }

    /**
     * admin_delete method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function admin_delete($id = null) {
        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        $this->request->allowMethod('post', 'delete');
        if ($this->User->delete()) {
            $this->Session->setFlash(__('The user has been deleted.'));
        } else {
            $this->Session->setFlash(__('The user could not be deleted. Please, try again.'));
        }
        return $this->redirect(array('action' => 'index'));
    }

    private function pre_register() {
        //debug($this->request->data);
        if ($this->request->data['pre']['age'] == 1 && $this->request->data['pre']['have_agent'] == 1 && ($this->request->data['pre']['is_union_member'] == 1 || $this->request->data['pre']['min_income'] == 1)) {
            $this->Session->setFlash(__(''));
            $this->Session->write('level', 2);
            $this->Session->write('is_union_member', $this->request->data['pre']['is_union_member']);
        } else {
            $this->Session->write('level', -1);
        }
    }

    public function available($field, $value) {
        $this->autoRender = false;
        $conditions = array(
            'User.' . $field => $value
        );
        if ($this->User->hasAny($conditions)) {
            echo 'User ' . $field . " already in use";
        } else {
            echo 'User ' . $field . " available";
        }
    }

    public function em_login() {
        return $this->redirect(Router::url('/login'));
    }

    public function parent_login() {
        return $this->redirect(Router::url('/login'));
    }

    public function beforeFilter() {
        parent::beforeFilter();
        // Allow users to register and logout.
        $this->Auth->allow();
        return;
        $this->Auth->allow('register', 'em_register', 'parent_register', 'add_parent_form');
    }

    public function login() {
        if ($this->request->is('post')) {
            if ($this->Auth->login()) {
				 $this->Session->write('level', $this->Auth->user('profile_status'));
				if($this->Auth->user('profile_status')=='100')
                return $this->redirect($this->Auth->redirect());
				elseif($this->Auth->user('role_id')==1){
				
                return $this->redirect(array('action'=>'admin_index'));
				}
				elseif($this->Auth->user('role_id')==2)
                return $this->redirect(array('action'=>'register','parent'=>true));

				elseif($this->Auth->user('role_id')==3)
                return $this->redirect(array('action'=>'register','em'=>true));

				elseif($this->Auth->user('role_id')==4)
                return $this->redirect(array('action'=>'register','yp'=>true));

				//$this->User->find('first',array('conditions'=>array('User.')));
                return $this->redirect($this->Auth->redirect());
            }
            $this->Session->setFlash(__('Invalid username or password, try again'));
        }
    }

    public function logout() {
        return $this->redirect($this->Auth->logout());
    }

}
